package com.binvshe.binvshe.mine.corporation;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.binvshe.binvshe.R;
import com.binvshe.binvshe.account.AccountManager;
import com.binvshe.binvshe.account.ParamKey;
import com.binvshe.binvshe.common.http.DataRequestListener;
import com.binvshe.binvshe.common.http.MyHttpRequest;
import com.binvshe.binvshe.common.http.UrlCenter;
import com.binvshe.binvshe.common.image.IML;
import com.binvshe.binvshe.mine.EditInfoActivity;
import com.binvshe.binvshe.mine.MineInfoActivity;
import com.binvshe.binvshe.mine.SignActivity;
import com.binvshe.binvshe.mine.utils.HeadUploadUtils;
import com.binvshe.binvshe.mine.view.ChooseCityDialog;
import com.binvshe.binvshe.organization.entity.ClubEntity;
import com.pachong.android.baseuicomponent.activity.BaseActivity;
import com.pachong.android.framework.httprequest.IHttpRequest;
import com.pachong.android.framework.picture.clipimage.PhotoActionHelper;
import com.pachong.android.framework.picture.picker.release.SelectAlbumActivity;
import com.pachong.android.framework.picture.picker.utils.FileManager;
import com.pachong.android.frameworkbase.customviews.iconcontent.IconTextArrowButton;
import com.pachong.android.frameworkbase.dialog.IOSAlertListFragment;
import com.pachong.android.frameworkbase.utils.BitmapUtil;
import com.pachong.android.frameworkbase.utils.EasyToast;

import org.json.JSONException;
import org.json.JSONObject;

import butterknife.Bind;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;

public class ClubInfoActivity extends BaseActivity {

    @Bind(R.id.mItbtnClubHead)
    IconTextArrowButton mItbtnClubHead;
    @Bind(R.id.mItbtnClubName)
    IconTextArrowButton mItbtnClubName;
    @Bind(R.id.mItbtnClubAddress)
    IconTextArrowButton mItbtnClubAddress;
    @Bind(R.id.mItbtnClubSign)
    TextView mItbtnClubSign;

    private static final int REQUEST_NAME = 626;
    private static final int REQUEST_SIGN = 816;
    public static final int TAKE_PHOTO_REQUEST = 449;
    public static final int SELECT_ALBUM_REQUEST = 540;
    public static final int REQUEST_KEY = 585;
    public static final String INTENT_SELECTED_PICTURE = "INTENT_SELECTED_PICTURE";
    private String mHeadUrl;
    private CircleImageView mCivHead;
    private String mFilename = "/" + System.currentTimeMillis() + ".png";
    private String mFilePath = null;
    private ClubEntity mMyClubBean;

    enum PutMessage {
        ClubHead,
        ClubName,
        Province,
        City,
        ClubSign,
    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    public static void start(Context context) {
        Intent starter = new Intent(context, ClubInfoActivity.class);
        context.startActivity(starter);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        enableBackButton();
        getCustomToolbar().setTitle("修改资料");
        initView();
        onGetUserInfo();
    }

    private void onGetUserInfo() {
        setUserInfo(AccountManager.getCurrentAccount().getClub());
    }

    private void setUserInfo(ClubEntity club) {
        mMyClubBean = club;
        refreshUserInfo();
    }

    private void refreshUserInfo() {
        if (mMyClubBean == null) {
            return;
        } else {
            mItbtnClubName.setSubText(mMyClubBean.getName());
            mItbtnClubAddress.setSubText(mMyClubBean.getProvince() + " " + mMyClubBean.getCity());
            mItbtnClubSign.setText(mMyClubBean.getSign());
            IML.load(this, mCivHead, mMyClubBean.getPortrait());
        }
    }

    private void initView() {
        LinearLayout.LayoutParams civheadLytParams = new LinearLayout.LayoutParams((int) getResources().getDimension(R.dimen.circleNormal), (int) getResources().getDimension(R.dimen.circleNormal));
        mCivHead = new CircleImageView(this);
        mItbtnClubHead.addSubView(mCivHead, civheadLytParams, Gravity.RIGHT | Gravity.CENTER_VERTICAL);

        mFilePath = FileManager.getImagePath(this);
    }

    @Override
    public View createDataView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.act_club_info, null);
    }

    @OnClick({R.id.mItbtnClubHead, R.id.mItbtnClubName, R.id.mItbtnClubAddress, R.id.mLintbtnClubSign})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.mItbtnClubHead:
                showIOSAlertFrag();
                break;
            case R.id.mItbtnClubName:
                EditInfoActivity.start(this, mMyClubBean.getName(), REQUEST_NAME);
                break;
            case R.id.mLintbtnClubSign:
                SignActivity.start(this, mMyClubBean.getSign(), REQUEST_SIGN);
                break;
            case R.id.mItbtnClubAddress:
                ChooseCityDialog chooseCityDialog = new ChooseCityDialog();
                chooseCityDialog.show(getSupportFragmentManager(), "tag");
                chooseCityDialog.setOnClickable(new ChooseCityDialog.ProvinceClickable() {
                    @Override
                    public void btnEnter(String province, String city) {
                        mItbtnClubAddress.setSubText(province + " " + city);
                        mMyClubBean.setProvince(province);
                        onPutUserInfo(PutMessage.Province);
                        mMyClubBean.setCity(city);
                        onPutUserInfo(PutMessage.City);
                    }
                });
                break;
        }
    }

    private void showIOSAlertFrag() {
        final IOSAlertListFragment diaFrag = new IOSAlertListFragment();
        String strArr = "从照片库选择";
        diaFrag.setActionList(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position == 0) {
                    Intent intentPickPhoto = new Intent(ClubInfoActivity.this, SelectAlbumActivity.class);
                    intentPickPhoto.putExtra(SelectAlbumActivity.RELEASE_IMGS_NUM, 0);
                    intentPickPhoto.putExtra(SelectAlbumActivity.INTENT_MAX_NUM, 1);
                    startActivityForResult(intentPickPhoto, MineInfoActivity.SELECT_ALBUM_REQUEST);
                }
                diaFrag.dismiss();
            }
        }, strArr).show(getSupportFragmentManager());
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        String changetext = null;
        if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_NAME || requestCode == REQUEST_SIGN) {
                changetext = data.getExtras().getString(EditInfoActivity.RESULT_STRING);
                switch (requestCode) {
                    case REQUEST_NAME:
                        mItbtnClubName.setSubText(changetext);
                        mMyClubBean.setName(changetext);
                        onPutUserInfo(PutMessage.ClubName);
                        break;
                    case REQUEST_SIGN:
                        mItbtnClubName.setSubText(changetext);
                        mMyClubBean.setSign(changetext);
                        onPutUserInfo(PutMessage.ClubSign);
                        break;
                }
            } else if (requestCode == SELECT_ALBUM_REQUEST) {
                mHeadUrl = data.getExtras().getStringArrayList(INTENT_SELECTED_PICTURE).get(0);
                clipImage(mHeadUrl, mFilePath + mFilename);
            } else if (requestCode == REQUEST_KEY) {
                //图片压缩上传 (80*80)
                setBitmapSize();
                sendRequest();
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void sendRequest() {
        HeadUploadUtils.uploadHead(this, mFilePath + mFilename, new HeadUploadUtils.HeadUploadable() {
            @Override
            public void onSuccess(String url) {
                mMyClubBean.setPortrait(url);
                onPutUserInfo(PutMessage.ClubHead);
            }

            @Override
            public void onFailureUpload(Throwable t, int errorNo, String strMsg) {
            }
        });
    }

    private void setBitmapSize() {
        Bitmap userHeader = BitmapUtil.decodeBitmapFromFilePath(mFilePath + mFilename, 80, 80);
        BitmapUtil.saveBitmap(userHeader, mFilePath + mFilename, true);
    }

    private void clipImage(String url, String outputUrl) {
        int maxWidth = 0;
        int windowWidth = this.getWindow().getWindowManager().getDefaultDisplay().getWidth();
        if (windowWidth <= 480) {
            maxWidth=100;
        }
        PhotoActionHelper.clipImage(this)
                .input(url)
                .output(outputUrl)
                .maxOutputWidth(maxWidth)
                .requestCode(REQUEST_KEY)
                .start();
    }

    private void onPutUserInfo(PutMessage message) {
        IHttpRequest request = new MyHttpRequest(this);
        JSONObject jobj = new JSONObject();
        try {
            jobj.put(ParamKey.Club.ID, mMyClubBean.getId());
            switch (message) {
                case ClubHead:
                    jobj.put(ParamKey.PORTRAIT, mMyClubBean.getPortrait());
                    break;
                case ClubName:
                    jobj.put(ParamKey.Club.NAME, mMyClubBean.getName());
                    break;
                case Province:
                    jobj.put(ParamKey.PROVINCE, mMyClubBean.getProvince());
                    break;
                case City:
                    jobj.put(ParamKey.CITY, mMyClubBean.getCity());
                    break;
                case ClubSign:
                    jobj.put(ParamKey.SIGN, mMyClubBean.getSign());
                    break;
            }

            request.put(UrlCenter.CLUB_UPDATE, jobj, new DataRequestListener<Object>(Object.class) {
                @Override
                public void onSuccess(Object reg) {
                    setUserInfo(mMyClubBean);
                }

                @Override
                public void onStart(Context context, String url) {
                    enableProgress(false);
                    super.onStart(context, url);
                }

                @Override
                public void onFailure(Throwable t, int errorNo, String strMsg) {
                    EasyToast.showToast(ClubInfoActivity.this, strMsg);
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}